const categoryModel = require("../model/adminCategoryModel");

module.exports = {
  addNewCategory(req, res) {
    // console.log(res);
    categoryModel.addNewCategory(req.body, (err, result) => {
      console.log(req.body);
      if (err) console.error(err);
      let resObj = {};
      if (result.affectedRows == 1) {
        resObj.code = 200;
        resObj.msg = "操作成功";
        let inserId = result.insertId;
        //操作成功后还需要把id返回来给浏览器，动态生成页面
        categoryModel.getCategoryById(inserId, (err, result) => {
          if (err) console.error(err);
          if (result) {
            resObj.data = result;
          } else {
            resObj.msg = "查不到数据";
          }
          res.send(resObj);
        });
      } else {
        resObj.code = "200";
        resObj.msg = "操作失败";
        res.send(resObj);
      }
    });
  },
  deleteCategoryById(req, res) {
    categoryModel.deleteCategoryById(req.query.id, (err, result) => {
      if (err) console.error(err);
      let resObj = {};
      if (result) {
        resObj.code = 200;
        resObj.msg = "获取成功";
        resObj.data = result;
      } else {
        resObj.code = 401;
        resObj.msg = "获取失败";
      }
      res.send(resObj);
    });
  },
  getCategoryById(req, res) {
    categoryModel.getCategoryById(req.query.id, (err, result) => {
      if (err) console.error(err);
      let resObj = {};
      if (result) {
        resObj.code = 200;
        resObj.msg = "获取成功";
        resObj.data = result;
      } else {
        resObj.code = 401;
        resObj.msg = "获取失败";
      }
      res.send(resObj);
    });
  },
  editCategoryById(req, res) {
    let { id, name, slug, classname } = req.body;
    categoryModel.editCategoryById(
      id,
      { name, slug, classname },
      (err, result) => {
        if (err) console.error(err);
        let resObj = {};
        if (result.affectedRows == 1) {
          resObj.code = 200;
          resObj.msg = "操作成功";
        } else {
          resObj.code = 401;
          resObj.msg = "操作失败";
        }
        res.send(resObj);
      }
    );
  },
  deleteMultiple(req, res) {
    categoryModel.deleteMultiple(req.query.ids, (err, result) => {
      if (err) console.error(err);
      let resObj = {};
      if (result.affectedRows != 0) {
        resObj.code = 200;
        resObj.msg = "操作成功";
      } else {
        resObj.code = 401;
        resObj.msg = "操作失败";
      }
      res.send(resObj);
    });
  }
};
